﻿using System.Diagnostics.Contracts;
using Manager.Model;
using Manager.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Manager.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly UserService userService;
        private readonly UserServiceByDapper userServiceByDapper;

        public UserController(UserService userService, UserServiceByDapper userServiceByDapper)
        {
            this.userService = userService;
            this.userServiceByDapper = userServiceByDapper;
        }

        [HttpGet("users")]
        public async Task<ObjectResult> GetPagedUsers(
            int pageNumber,
            int pageSize,
            string? username,
            string? sex,
            string? state
        )
        {
            var users = await userService.GetUsersPaged(pageNumber, pageSize, username, sex, state);
            var count = await userService.GetTotalUsersCountAsync();
            return new ObjectResult(
                new
                {
                    success = true,
                    records = users,
                    total = count
                }
            );
        }

        [HttpGet("detail")]
        public ObjectResult GetUserById(int id)
        {
            var user = userService.GetUserById(id);
            return new ObjectResult(new { success = true, user });
        }

        [HttpPut("update")]
        public ObjectResult UpdateUser(User user)
        {
            var upUser = userService.UpdateUser(user);
            return new ObjectResult(new { success = true, user = upUser });
        }

        [HttpDelete("id")]
        public ObjectResult DeleteUser(int id)
        {
            userService.DeleteUserById(id);
            return new ObjectResult(new { success = true });
        }

        [HttpGet("all")]
        public async Task<ObjectResult> GetAllUsers()
        {
            var users = await userServiceByDapper.GetAllUsers();
            return new ObjectResult(new { success = true, users });
        }
    }
}
